package cn.dida.controller.upload;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.UUID;

/**
 * <p>默认文件存储设置</p>
 * @author weiwei
 *
 */
public class DefaultFileStorage implements FileStorage {

	/**
	 * 文件存储
	 * @param is 输入流
	 * @param originalFilename 文件原名称
	 * @return String 文件全路径和名称
	 */
    @Override
    public String store(InputStream is, String originalFilename) throws IOException {
        //step1:构建文件输出路径
        String uploadDir = getUploadDir();
        String fileDir = generateFileDir(originalFilename);
        String fileName = generateFileName(originalFilename);

        //step2:判断输出目录是否为空，为空则创建
        File tmp = new File(uploadDir + "/" + fileDir);
        if (!tmp.exists()) {
            tmp.mkdirs();
        }
        //step3:存储文件
        int isSize = is.available();
        String outFilePath = uploadDir + "/" + fileDir + "/" + fileName;

        OutputStream os = new FileOutputStream(new File(outFilePath));
        IOUtils.copy(is, os);
        os.close();

        return "/" + fileDir + "/" + fileName;
    }

    public String getReturnPath(String outFilePath) {
        return outFilePath;
    }

    @Override
    public void delete(String... paths) throws IOException {
        for (String filePath : paths) {
            String uploadDir = getUploadDir();
            File file = new File(uploadDir + "/" + filePath);
            if (file.exists()) {
                FileUtils.forceDelete(file);
            }
        }
    }

    protected String generateFileName(String originalFilename) {
        String uuid = UUID.randomUUID().toString();
        uuid = uuid.replaceAll("-", "");
        String fileName = uuid + "." + originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
        return fileName;
    }

    protected String generateFileDir(String originalFilename) {
        Calendar now = Calendar.getInstance();
        DecimalFormat decimalFormat = new DecimalFormat("00");
        String fileDir = "imgs/" + now.get(Calendar.YEAR) + "/" + decimalFormat.format(now.get(Calendar.MONTH) + 1) + decimalFormat.format(now.get(Calendar.DATE));
        return fileDir;
    }

    protected String getUploadDir() {
        String uploadDir = "F:/NginxWeb";
        return uploadDir;
    }

}
